﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Leeder.Logger;
using Pipelines.Sockets.Unofficial;
using System.Threading;
using SevenZip.Buffer;

namespace NewAndong.Handle
{
    public class SockeHandler
    {
        private LogOperate LogObj => Log.GetLogger(this.GetType());
        private Socket serverSocket;
        private Socket clientSocket;

        public void StartServer(string ip, int port)
        {
            lockobj = new object();
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
            serverSocket.Listen(5);
            serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            clientSocket = serverSocket.EndAccept(ar);
            byte[] buffer = new byte[1024];
            clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), buffer);

            EndPoint remoteEndPoint = clientSocket.RemoteEndPoint;
            if (remoteEndPoint != null)
            {
                IPAddress remoteIP = ((IPEndPoint)remoteEndPoint).Address;
                LogObj.Info("一个客户端建立连接: " + remoteIP.ToString());
            }
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            byte[] buffer = (byte[])ar.AsyncState;
            int bytesRead = clientSocket.EndReceive(ar);
            string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);

            // 处理接收到的数据
            LogObj.Debug(DateTime.Now + "TCP接收数据: " + data);
            if (data == "ping")
            {
                SendMessageToClient("pong");
            }
            // 继续接收数据
            buffer = new byte[1024];
            clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), buffer);
        }

        public void Close()
        {
            serverSocket.Close();
            if (clientSocket != null)
            {
                clientSocket.Close();
            }
        }

        public void SendMessageToClient(string message)
        {
            if(clientSocket == null)
            {
                LogObj.Error("客户端未连接,无法发送数据");
                return;
            }
            byte[] buffer = Encoding.ASCII.GetBytes(message);
            //clientSocket.Send(buffer);
            Send(clientSocket, buffer);
        }

        object lockobj;
        private void Send(Socket socket, byte[] buffer)
        {
            lock (lockobj)
            {
                socket.Send(buffer);
            }
        }

    }
}
